package com.woniuxy.rabbit.service;

import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.woniuxy.common.dto.SkuDto;
import com.woniuxy.common.dto.UserDto;
import com.woniuxy.rabbit.feign.ProductFeign;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import javax.servlet.http.HttpServletRequest;

import static com.woniuxy.common.constant.FinanceConstant.Exchange.ORDER_EXCHANGE;
import static com.woniuxy.common.constant.FinanceConstant.RabbitMq.*;
import static com.woniuxy.common.utils.UserUtil.getUser;
import static com.woniuxy.rabbit.utils.MessageUtil.sendMessage;

@Service
public class OrderService {


    @Autowired
    private ProductFeign productFeign;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private HttpServletRequest request;

    @Autowired
    private StringRedisTemplate redisTemplate;


    public String addOrder(Integer skuId){
        //下单超过30分钟没有支付则回滚订单库存金融数据（延时队列）
        //发送3个消息：
        // 订单参数：购买的金额，商品（调用商品服务），用户，订单号
        Long orderId = IdUtil.getSnowflake(1, 1).nextId();
        UserDto user = getUser(request);
        SkuDto sku = productFeign.queryByid(skuId);
        JSONObject order = new JSONObject();
        order.put(ORDER_ID,orderId);
        order.put(USER,user);
        order.put(SKU,sku);




        //订单
//        rabbitTemplate.convertAndSend(ORDER_EXCHANGE,"order.routing.key",order.toString());
        sendMessage(ORDER_EXCHANGE,"order.routing.key",order.toString(),rabbitTemplate,redisTemplate);
        //分期
//        rabbitTemplate.convertAndSend(ORDER_EXCHANGE,"consume.routing.key",order.toString());
        sendMessage(ORDER_EXCHANGE,"consume.routing.key",order.toString(),rabbitTemplate,redisTemplate);
        // 库存：商品
//        rabbitTemplate.convertAndSend(ORDER_EXCHANGE,"sku.routing.key",skuId.toString());
        sendMessage(ORDER_EXCHANGE,"sku.routing.key",skuId.toString(),rabbitTemplate,redisTemplate);
        //延时队列：订单
//        rabbitTemplate.convertAndSend(ORDER_EXCHANGE,"ttl.routing.key", orderId.toString());
        sendMessage(ORDER_EXCHANGE,"ttl.routing.key",orderId.toString(),rabbitTemplate,redisTemplate);

        return "下单成功";
    }

    /**
     * 发消息
     * @param receivedExchang
     * @param receivedRoutingKey
     * @param msg
     */

}
